package com.just.sxmiaosha.utils;


import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.just.sxmiaosha.dao.StockDao;
import com.just.sxmiaosha.entity.Stock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * @author xiao.shu
 * @date on 2020/11/12 10:33
 * @description
 * @Copyright (c)
 */
@Slf4j
@Component
public class StockLocalCache {

    //方式一
    private static LoadingCache<Long, Stock> cache = CacheBuilder.newBuilder().refreshAfterWrite(3, TimeUnit.HOURS)// 给定时间内没有被读/写访问，则回收。
            .expireAfterAccess(1L, TimeUnit.HOURS)// 缓存过期时间和redis缓存时长一样
            .maximumSize(1000).// 设置缓存个数
            build(new CacheLoader<Long, Stock>() {
        @Override

        public Stock load(Long appKey) {
            log.info("当本地缓存命没有中时,查询数据库 ");
            return getAppkeyInfo(appKey);
        }


    });


    private static Stock getAppkeyInfo(Long appKey) {
        log.info("method<getAppkeyInfo> get AppkeyInfo form DB appkey<" + appKey + ">");
        Stock Stock = SpringUtil.getBean(StockDao.class).getStockCountById(appKey.intValue());
        log.info("查询出来的数据:{}", Stock == null ? null : Stock.toString());
        return Stock;
    }

    public static Stock getAppkeyInfoByAppkey(Long appKey) throws ExecutionException {
        log.info("method<getAppkeyInfoByAppkey> appkey<" + appKey + ">");
        return cache.get(appKey);
    }


    //方式二
    public static Stock getCallableData(Long key) throws ExecutionException {
        return cache.get(key, new Callable<Stock>() {
            @Override
            public Stock call() {
                //获取数据
                return getAppkeyInfo(key);
            }
        });

    }
}
